package json

import (
	"bytes"
	"encoding/json"
)

type Raw = json.RawMessage

func Bind(src []byte, t interface{}) error {
	return json.Unmarshal(src, t)
}

func BindFromString(src string, t interface{}) error {
	return Bind([]byte(src), t)
}

func BindFromMap(src map[string]interface{}, t interface{}) error {
	return Bind(Dump(src), t)
}

func MustBind(src []byte, t interface{}) {
	if err := Bind(src, t); err != nil {
		panic("must bind json failed:" + err.Error())
	}
}

func MustBindFromString(src string, t interface{}) {
	if err := BindFromString(src, t); err != nil {
		panic("must bind json failed:" + err.Error())
	}
}

func Dump(t interface{}) []byte {
	res, _ := json.Marshal(t)
	return res
}

func DumpString(t interface{}) string {
	res, _ := json.Marshal(t)
	return string(res)
}

func DumpMap(t interface{}) map[string]interface{} {
	res := make(map[string]interface{}, 0)
	_ = json.Unmarshal(Dump(t), &res)
	return res
}

func FormatDumpString(t interface{}) string {
	var str bytes.Buffer
	raw := Dump(t)
	if err := json.Indent(&str, raw, "", "  "); err != nil {
		return string(raw) + "[" + err.Error() + "]"
	}
	return str.String()
}
